package com.phicomm.envmonitor.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import com.phicomm.envmonitor.R;
import com.phicomm.envmonitor.adapters.EquipmentChoseAdapter;
import com.phicomm.envmonitor.base.BaseFragment;
import com.phicomm.envmonitor.models.equipment.EquipmentItem;
import com.phicomm.envmonitor.utils.FragmentUtils;
import com.phicomm.envmonitor.utils.LogUtils;
import com.phicomm.envmonitor.views.CountDownView;
import com.phicomm.envmonitor.views.TipDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.fogcloud.sdk.easylink.api.EasyLink;
import io.fogcloud.sdk.easylink.helper.EasyLinkCallBack;
import io.fogcloud.sdk.easylink.helper.EasyLinkParams;
import io.fogcloud.sdk.mdns.api.MDNS;
import io.fogcloud.sdk.mdns.helper.SearchDeviceCallBack;

/**
 * Created by zhangjian on 2017/2/23.
 */

public class OnboardingDeviceSetFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    private static final int RUNTIME = 60000;
    private static final int SLEEPTIME = 20;
    private static final int UPDATE = 0;

    @BindView(R.id.iv_back)
    ImageView mImageViewBack;
    @BindView(R.id.tv_count_down)
    CountDownView mCountDownView;

    @BindView(R.id.lv_equipments)
    ListView mListViewEquip;
    @BindView(R.id.btn_connect)
    Button mButtonConnect;
    List<EquipmentItem> mEquipmentList = new ArrayList<>();
    EquipmentChoseAdapter mEquipChoseAdapter;

    int mSelectedPosition = 0;
    EasyLink mEasyLink;
    EasyLinkParams mEasyLinkParams;
    MDNS mMDNS;
    String mSsid;
    String mPassword;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE:
                    mEquipChoseAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return init(inflater.inflate(R.layout.fragment_onboard_equip_chose, container, false));
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        mCountDownView.setOnTickListener(new CountDownView.OnTickListener() {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void Finish() {
                if (mEquipmentList.size() == 0) {
                    showTipDialog(R.string.fail_to_find_device, R.string.sure, new TipDialog.OnTipButtonClickListener() {
                        @Override
                        public void onSure() {
                            //zhongfei.sun change for ACA-13 at 2017-3-21
                            FragmentUtils.exitF(getActivity());
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void initWorks() {
        super.initWorks();
        mTitleTextView.setText(R.string.onboard_title);
        Bundle args = getArguments();
        mSsid = args.getString("ssid");
        mPassword = args.getString("password");
        setEquipmentList();
        startSearch(mSsid, mPassword);
        startCounter();

        mEquipChoseAdapter = new EquipmentChoseAdapter(getActivity(), mEquipmentList);
        mListViewEquip.setAdapter(mEquipChoseAdapter);
        mListViewEquip.setOnItemClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSearch();
        stopCounter();
        LogUtils.log("debug", "onDestroy!");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //进行选中设备处理逻辑，即选中设备图标变成选中状态，其他设备变成为选中状态
        for (int i = 0; i < mEquipmentList.size(); i++) {
            mEquipmentList.get(i).isSelected = (i == position);
        }
        mSelectedPosition = position;
//        mEquipChoseAdapter.notifyDataSetChanged();

        if (mEquipmentList != null && !mEquipmentList.isEmpty()) {
            stopSearch();
            stopCounter();
            Bundle args = new Bundle();
            args.putString("macId", mEquipmentList.get(mSelectedPosition).equipmentId);
            FragmentUtils.nextF(getActivity(), R.id.activity_onboarding, this, new OnboardingConnectFragment(), args);
        }
    }

    @OnClick(R.id.iv_back)
    public void back() {
        stopSearch();
        stopCounter();
        FragmentUtils.exitF(getActivity());
    }

    @OnClick(R.id.btn_connect)
    public void goConnect() {
        //发送连接设备的请求到云端
        if (mEquipmentList != null && !mEquipmentList.isEmpty()) {
            stopSearch();
            stopCounter();
            Bundle args = new Bundle();
            args.putString("macId", mEquipmentList.get(mSelectedPosition).equipmentId);
            FragmentUtils.nextF(getActivity(), R.id.activity_onboarding, this, new OnboardingConnectFragment(), args);
        }
    }

    public void setEquipmentList() {
        mEquipmentList.clear();
    }

    //开启搜索设备
    private void startSearch(String ssid, String password) {
        startEasyLink(ssid,password);
        startSearchDevice();
    }

    private void startEasyLink(String ssid, String password) {
        //开启EasyLink服务
        if (mEasyLink != null || mMDNS != null) {
            stopSearch();
        }
        mEasyLink = new EasyLink(getActivity());
        mEasyLinkParams = new EasyLinkParams();
        mEasyLinkParams.ssid = ssid;
        mEasyLinkParams.password = password;
        mEasyLinkParams.runSecond = RUNTIME;
        mEasyLinkParams.sleeptime = SLEEPTIME;
        mEasyLink.getSSID();
        mEasyLink.startEasyLink(mEasyLinkParams, new EasyLinkCallBack() {
            @Override
            public void onSuccess(int i, String s) {
            }

            @Override
            public void onFailure(int i, String s) {
            }
        });
    }

    private void startSearchDevice() {
        //开启mdns服务
        mMDNS = new MDNS(getActivity());
        mMDNS.startSearchDevices("_easylink_config._tcp.local.", new SearchDeviceCallBack() {
            @Override
            public void onDevicesFind(int code, JSONArray jsonArray) {
                super.onDevicesFind(code, jsonArray);
                LogUtils.log("debug", "jsonArray" + jsonArray.toString());
                if (jsonArray.toString() != null && !"".equals(jsonArray.toString()) && jsonArray.length() > 0) {
                    try {
                        JSONArray json = new JSONArray(jsonArray.toString());
                        JSONObject jo;
                        int size = json.length();
                        String mac = "";
                        String name = "";
                        for (int i = 0; i < size; i++) {
                            jo = new JSONObject(json.get(i).toString());
                            mac = jo.optString("MAC");
                            name = jo.optString("Name");
                            boolean isHave = false;
                            if (mEquipmentList.size() == 0) {
                                mEquipmentList.add(new EquipmentItem(mac, name, false));
                                Message msg = Message.obtain();
                                msg.what = UPDATE;
                                mHandler.sendMessage(msg);
                            } else {
                                for (EquipmentItem equipmentItem : mEquipmentList) {
                                    if (equipmentItem.equipmentId.equals(mac)) {
                                        isHave = true;
                                        break;
                                    }
                                }
                                if (!isHave) {
                                    // have add action
                                    mEquipmentList.add(new EquipmentItem(mac, name, false));
                                    Message msg = Message.obtain();
                                    msg.what = UPDATE;
                                    mHandler.sendMessage(msg);
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onSuccess(int code, String message) {
                super.onSuccess(code, message);
            }

            @Override
            public void onFailure(int code, String message) {
                super.onFailure(code, message);
            }
        });
    }

    private void stopSearch() {
        stopEasyLink();
        stopSearchDevice();
    }

    private void stopEasyLink() {
        if (mEasyLink != null) {
            mEasyLink.stopEasyLink(new EasyLinkCallBack() {
                @Override
                public void onSuccess(int code, String message) {

                }

                @Override
                public void onFailure(int code, String message) {

                }
            });
            mEasyLink = null;
        }
    }

    private void stopSearchDevice() {
        if (mMDNS != null) {
            mMDNS.stopSearchDevices(new SearchDeviceCallBack() {
                @Override
                public void onSuccess(int code, String message) {
                    super.onSuccess(code, message);
                }

                @Override
                public void onFailure(int code, String message) {
                    super.onFailure(code, message);
                }
            });
            mMDNS = null;
        }
    }

    private void startCounter() {
        mCountDownView.start();
    }

    private void stopCounter() {
        mCountDownView.stop();
    }
}
